//
// Created by Tommy on 15/3/23.
// Copyright (c) 2015 com.koala. All rights reserved.
//

#import "NSObject+KLExecuteOnDealloc.h"
#import "KLRuntime.h"


@interface __KLExecuteOnDeallocInternalObject : NSObject
@property(nonatomic, copy) void (^deallocBlock)(id);
@property(nonatomic, weak) id obj;

- (id)initWithBlock:(void (^)(id))aBlock;
@end

@implementation __KLExecuteOnDeallocInternalObject

- (id)initWithBlock:(void (^)(id))aBlock
{
    self = [super init];
    if (self) {
        _deallocBlock = [aBlock copy];
    }
    return self;
}

- (void)dealloc {
    if (_deallocBlock) {
        _deallocBlock(_obj);
        _deallocBlock = nil;
    }
}
@end


@implementation NSObject (KLExecuteOnDealloc)


- (void *)kl_performBlockOnDealloc:(void (^)(id))aBlock {
    __KLExecuteOnDeallocInternalObject *internalObject = [[__KLExecuteOnDeallocInternalObject alloc] initWithBlock:aBlock];
    internalObject.obj = self;
    objc_setAssociatedObject(self, (__bridge void*)(internalObject), internalObject, OBJC_ASSOCIATION_RETAIN);
    return (__bridge void*) internalObject;
}


- (void)kl_cancelDeallocBlockWithKey:(void*)blockKey {
    __KLExecuteOnDeallocInternalObject *internalObject = objc_getAssociatedObject(self, blockKey);
    internalObject.deallocBlock = nil;
    objc_setAssociatedObject(self, blockKey, nil, OBJC_ASSOCIATION_ASSIGN);
}
@end